<template>
  <view class="wrapper">
    <view class="result">
      <view class="analyze">
        <view class="analyze-total">
            <view>月供(元)</view>
            <text>{{ this.formatNum(loanDetail.monthPay) || '--' }}</text>
        </view>
        <view class="analyze-detail">
            <view class="left">
                <view>支付利息(元)</view>
                <view>{{this.formatNum(loanDetail.totalInterest) || '--'}}</view>
            </view>
            <view class="right">
                <view>还款总额(元)</view>
                <view>{{this.formatNum(loanDetail.totalMoney) || '--'}}</view>
            </view>
        </view>
      </view>
    </view>
    <view class="calculator">
      <form @submit="confirm">
        <view class="form-item m_flex m_flex_center">
          <view class="label">类型</view>
          <radio-group name="loanmode" @change="selectMode">
            <label>
              <radio 
                value="0" 
                style="transform:scale(0.7)"
                :checked="form.loanmode == 0"
                color="#007eff"
              />
              <text>等额本金</text>
            </label>
            <label>
              <radio 
                value="1"
                style="transform:scale(0.7)" 
                :checked="form.loanmode == 1"
                color="#007eff"
              />
              <text>等额本息</text>
            </label>
          </radio-group>
        </view>
        <view class="form-item m_flex m_flex_center">
          <view class="label">贷款金额</view>
          <input 
            type="digit" 
            class="flex_1 bordered" 
            placeholder="贷款金额" 
            name="loanAmount"
            :value="form.loanAmount"
            @input="changeAmount"
          />
        </view>
        <view class="form-item m_flex m_flex_center">
          <view class="label">贷款利率</view>
          <input 
            @input="changeRate" 
            type="digit" 
            class="flex_1 bordered" 
            placeholder="贷款利率" 
            name="loanRate"
            :value="form.loanRate"
          />
          <view class="addon">%</view>
        </view>
        <view class="form-item m_flex m_flex_center">
          <view class="label">按揭年数</view>
          <picker
            :value="pickerValue"
            mode="selector" 
            :range="options" 
            @change="selectMonth" 
            class="flex_1 text-r"
          >
              <text v-if="!form.loanMonths">请选择</text>
              <text v-else>{{form.loanMonths / 12}}年 ({{form.loanMonths}}期)</text>
              <image src="../../assets/arrow.png" alt="" class="arrow" />
          </picker>
        </view>
        <view class="footer m_flex">
          <button :loading="loading" 
            class="flex_1 mr-16 color-blue m_button" form-type="submit"
          >计算</button>
          <button @click="reset" type="default" class="flex_1 m_button">重置</button>
        </view>
      </form>
    </view>
    <view class="details" v-if="loanDetail.monthlyPays && loanDetail.monthlyPays.length">
      <view class="details-label">每月还款明细</view>
      <view class="header m_flex m_flex_center">
        <view class="col col1">月份</view>
        <view class="col">月供金额</view>
        <view class="col">剩余本金</view>
        <view class="col">剩余总额</view>
      </view>
      <view class="details-list">
        <view v-for="(item) in loanDetail.monthlyPays" :key="item.yearIdx">
          <view class="item">
            <view class="item-label">第{{item.yearIdx}}年</view>
            <view class="body m_flex row m_flex_center" v-for="row in item.details" :key="row.seqMonth">
              <view class="col col1">{{row.seqMonth % 12 ? row.seqMonth % 12 : 12 }}月</view>
              <view class="col">{{this.formatNum(row.monthPay)}}</view>
              <view class="col">{{this.formatNum(row.releaseLoan)}}</view>
              <view class="col">{{this.formatNum(row.releaseTotal)}}</view>
            </view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { HOST } from '../../const.js';

export default {
  data() {
    return {
      loading: false,
      form: {
        loanmode: '0',
        loanAmount: undefined,
        loanMonths: 360,
        loanRate: undefined
      },
      loanDetail: {}
    }
  },
  onLoad() {},
  computed: {
     options() {
      return Array(30).fill(1).map((_d, index) => `${index + 1}年 (${(index + 1) * 12}期)`);
    },
    pickerValue() {
      return +this.form.loanMonths / 12 - 1;
    }
  },
  methods: {
    formatNum(str) {
      if(!str) return str;
      const reg = /(?<=(^|\s)\d+)(?=(\d{3})+\b)/g;
      return String(str).replace(reg, ',');
    },
    validation() {
      if(!this.form.loanAmount) {
        return {
          title: '请填写贷款金额',
          type: 'error',
          key: 'loanAmount'
        }
      }
      if(!this.form.loanRate) {
        return {
          title: '请填写贷款利率',
          type: 'error',
          key: 'loanAmount'
        }
      }
      return null
    },
    changeAmount(evt) {
      this.form.loanAmount = evt.detail.value;
    },
    changeRate(evt) {
      this.form.loanRate = evt.detail.value;
    },
    //计算
    confirm(evt) {
      // #ifdef  H5
      const url = '/api/loan';
      // #endif
      // #ifdef  MP-WEIXIN
      const url = HOST +'/api/loan';
      // #endif
      const message = this.validation();
      if(message) {
        uni.showToast({
          title: message.title,
          icon: 'none'
        })
        return
      }
      this.loading = true;
      uni.request({
        url,
        data: {
          ...this.form,
          loanAmount: +this.form.loanAmount,
          loanRate: this.form.loanRate / 100,
          loanmode: +this.form.loanmode
        },
        method: 'POST',
        success: (res) => {
          this.loading = false;
          if(res.data.msg == 'ok') {
            this.loanDetail = res.data.data;
            this.loanDetail.monthlyPays = this.transformLoan(this.loanDetail.monthlyPays);
          } else {
            uni.showToast({
              title: '网络异常',
              icon: 'none'
            })
          }
        },
        fail: () => {
          this.loading = false;
          uni.showToast({
              title: '网络异常',
              icon: 'none'
            })
        }
      })
    },
    // 重置
    reset() {
      this.form = {
        loanmode: '0',
        loanAmount: undefined,
        loanMonths: 360,
        loanRate: undefined
      };
      this.loanDetail = {};
    },
    autoCalc() {
      if(!this.form.loanAmount || !this.form.loanRate) return
      this.confirm();
    },
    selectMonth(evt) {
      const v = evt.detail.value;
      this.form.loanMonths = (+v + 1) * 12;
      this.autoCalc();
    },
    selectMode(evt) {
      this.form.loanmode = evt.detail.value;
      this.autoCalc();
    },
    // 处理还款明细
    transformLoan(list) {
      return list.reduce((acc, cur) => {
        const curYear = Math.ceil(cur.seqMonth / 12);
        
        if(!acc[curYear - 1]) {
          acc[curYear - 1] = {
            yearIdx: curYear,
            details: []
          };
        }
        acc[curYear - 1].details.push(cur);
        return acc;
      }, []);
    }
  },
}
</script>

<style>
.result {
  position: sticky;
  top: 0;
  /* #ifdef  H5 */
  top:88upx;
  /* #endif */
  z-index: 3;
  box-shadow:  0 0 5upx rgba(0,0,0,0.1)
}
.color-blue {
  background-color: #007eff;
  color: #fff;
}
.calculator {
  padding: 40upx;
  font-size: 28upx;
}

.input-placeholder {
  font-size: 28upx;
  color: #999;
}

.form-item {
  height: 64upx;
  margin-bottom: 32upx;
  position: relative;
}

.label {
    font-size: 28upx;
    color: #666;
    padding-right: 16upx;
}

.addon {
  height: 58upx;
  width: 80upx;
  border-radius: 8upx;
  line-height: 58upx;
  background: #f5f7fa;
  text-align: center;
  position: absolute;
  right: 2upx;
  top: 2upx;
}

.flex_1 {
  flex: 1;
}

.m_button {
  height: 64upx;
  line-height: 64upx;
  font-size: 28upx;
}

.m_button.color-blue::after{
  border-color: #007eff;
}

.bordered {
  border: 1PX solid #ebebeb;
  border-radius: 8upx;
  height: 64upx;
  padding: 0 8upx;
}

.m_flex {
  display: flex;
}

.m_flex_center {
  align-items: center;
}

.mr-16 {
  margin-right: 32upx;
}

.footer {
  margin-top: 20upx;
}

.analyze {
    background: #007eff;
    color: #fff;
}

.list {
    margin-top: 24upx;
}

.analyze-total {
    height: 240upx;
    text-align: center;
    display: flex;
    align-content: center;
    justify-content: center;
    flex-direction: column;
    font-size: 40upx;
}

.analyze-detail {
    display: flex;
    font-size: 28upx;
}
.analyze-detail .left, .analyze-detail .right {
    width: 50%;
    height: 140upx;
    display: flex;
    flex-direction: column;
    align-content: center;
    justify-content: center;
    text-align: center;
}

.details-label {
    font-weight: bold;
    position: relative;
    margin-left: 32upx;
    margin-bottom: 16upx;
}

.details-label::before {
    position: absolute;
    content: "";
    display: block;
    width: 12upx;
    background: #007eff;
    height: 28upx;
    top: 8upx;
    left: -16upx;
    border-radius: 8upx;
}


.row {
    height: 64upx;
    padding-left: 24upx;
    border-bottom: 1PX solid #ebebeb;
}

.details {
    margin-bottom: 100upx;
}
.text-r {
  text-align: right;
}

.arrow {
  height: 32upx;
  width: 32upx;
  vertical-align: middle;
}

.item .item-label {
  color: #666;
  padding: 0 24upx;
  height: 64upx;
  line-height: 64upx;
  background: rgba(0, 126,255, .3);
}

.body {
  padding: 0 24upx;
}

.header {
  height: 64upx;
  padding: 0 24upx;
  position: sticky;
  top: 460upx;
  z-index: 3;
  background: #fff;
  box-shadow:  0 0 5upx rgba(0,0,0,0.4);
  /* #ifdef MP-WEIXIN */
  top: 380upx;
  /* #endif */
}

.col {
  flex: 1;
  color: #666;
  font-size: 28upx;
}
.col1 {
  flex: 100upx 0 0;
}

.header .col {
  color: #007eff;
}
</style>
